# coding: utf-8

from flask import Blueprint, render_template, Flask, request, redirect, session
from app.utils.md5 import md5
from app.utils import helper

account = Blueprint('account', __name__)


@account.route('/login/', methods=['GET', 'POST'])
def login():
    print("登录界面")
    if request.method == 'POST':
        username = request.form.get('user')
        print("用户名: %s" % username)
        password = request.form.get('pwd')
        print("密码: %s" % password)
        pwd_md5 = md5(password)
        print("MD5密码: %s" % pwd_md5)

        data = helper.fetch_one("select id,nickname from user_info where user=%s and pwd=%s", (username, pwd_md5))
        if not data:
            return render_template('login.html', error='用户名密码错误')
        session['user_info'] = {'id': data['id'], 'nickname': data['nickname']}
        return redirect('/index/')
    return render_template('auth/login.html')


@account.route('/logout')
def logout():
    if 'user_info' in session:
        del session['user_info']

    return redirect('/login')
